﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ROrganizer.Client
{
    public class MetaRepository
    {
        public MetaEntry[] All()
        {
            using (ApplicationData.OpenSession(ApplicationData.MetaRepository))
            {
                var document = ApplicationData.GetDocument(ApplicationData.MetaRepository);
                var serializer = new MetaSerializer();
                var entries = serializer.Deserialize(document);

                return entries.Where(x => File.Exists(x.File.Path)).ToArray();
            }
        }

        public MetaEntry Get(string filename)
        {
            using (ApplicationData.OpenSession(ApplicationData.MetaRepository))
            {
                var document = ApplicationData.GetDocument(ApplicationData.MetaRepository);
                var serializer = new MetaSerializer();
                var entry = serializer.Deserialize(document, filename.ToLower());

                if (entry == null || !File.Exists(entry.File.Path))
                    return null;

                return entry;
            }
        }

        public void SaveOrUpdate(params MetaEntry[] entries)
        {
            using (ApplicationData.OpenSession(ApplicationData.MetaRepository))
            {
                var document = ApplicationData.GetDocument(ApplicationData.MetaRepository);
                var serializer = new MetaSerializer();

                serializer.Update(document, entries);
                ApplicationData.UpdateDocument(ApplicationData.MetaRepository, document);
            }
        }
    }
}
